var statusBar = null;
var bgImg = null;
var stopped = false;
var localCcMonitor = 'local.ccm'

var KEY_CONFIGURATION_SOURCE = 'cc_monitor_dsl_configuration_source';
var KEY_INTERVAL = 'cc_monitor_dsl_interval';
var KEY_MONITOR_URI = 'cc_monitor_dsl_uri';
var KEY_LOCAL_MONITOR = 'cc_monitor_dsl_local';

function init() {
  $('ccmonitor_uri').addEventListener('keydown', function(e) {
    if(e.keyCode == 13) {
      loadCcMonitor();
    }
  }, false);
  
  initConfiguration();
  initButton();
  statusBar = $('status-bar');
  statusBar.append = function(child) {
    statusBar.innerHTML += child
  }
  bgImg = $('bg-img')
  
  if(window.widget) {
    displayVersion();
    updateVersion();
  }
  
  if(window.widget) {
    window.widget.onshow = function() {
      if(!stopped) {
        $('spinner-img').src = 'images/observing-spinner.gif'
      }
      refresh();
    }
    
    window.widget.onhide = function() {
      stopRefreshOutput();
      // clear spinner.gif, for it make dashboard working while hidding
      statusBar.innerHTML = 'Reloading builds status report...';
      $('spinner-img').src = 'images/observing.png'
    }
    
    window.widget.onremove = function() {
      stopMonitors();
    }
  }
  
  statusBar.innerHTML = 'Waiting for builds status report to be created.'
  window.setTimeout(restartMonitors, 500);
}

var refreshOutputTimeId = null
function refreshOutput() {
  if(refreshOutputTimeId) {
    return;
  }
  refreshOutputTimeId = window.setInterval(refresh, 5*1000)
}

function stopRefreshOutput() {
  if(refreshOutputTimeId) {
    window.clearInterval(refreshOutputTimeId);
    refreshOutputTimeId = null;
  }
}

function refresh() {
  if($('front').style.display == 'none') {
    return;
  }
  if(window.widget) {
    refreshBuildsStatus();

    var ccmsRunning = isRunning();
    if(stopped && ccmsRunning) {
      stopMonitors();
    }
    if(!stopped && !ccmsRunning) {
      restartMonitors();
    }
  }
}

function refreshBuildsStatus() {
  var command = window.widget.system('./ccm -o', function() {
    var output = handleCommand(command)
    if(output && strip(output).length > 0) {
      statusBar.innerHTML = ''
      try {
        eval(output);
        stopRefreshOutput();
      } catch (e) {
        log("eval output error: " + e)
        window.setTimeout(refreshBuildsStatus, 100);
      }
    }
  });
}

function isRunning() {
  var command = window.widget.system('./ccm -r', null);
  var output = handleCommand(command)
  if(output && typeof(output) == "string" && output.length > 1) {
    return output.indexOf("ccms is running") > -1;
  }
  return false;
}

function restartMonitors() {
  $('spinner-img').src = 'images/observing-spinner.gif'
  $('start-button').hide();
  $('stop-button').show();
  setConfiguration();
  if(window.widget) {
    log("Starting...")
    stopped = false;
    window.widget.system('./ccm -s >& stdout.log &', null);
  }

  refreshOutput();
}

function setConfiguration() {
  if($('configuration_source').value == '') {
    window.setTimeout(showPrefs, 1000);
    return;
  }

  var intervalTime = interval();
  if(intervalTime < 10) {
    window.setTimeout(showPrefs, 1000);
    return
  }
  
  saveLocalCcMonitor();
  
  if(window.widget) {
    var f = $('configuration_source').value
    var command = window.widget.system('./ccm -f ' + f + ' -i ' + intervalTime, function() {
    })
    command.onreadoutput = function(output) {
      log(output)
    }
  }
}

function stopMonitors() {
  toStopStatus();
  if(window.widget) {
    log("Stopping...")
    window.widget.system('./ccm -t', function() {
      log('Stopped.')
    });
  }
}

function toStopStatus() {
  $('spinner-img').src = 'images/observing.png'
  $('stop-button').hide();
  $('start-button').show();
  stopped = true;
  stopRefreshOutput();
}

function log(message) {
  maxLen = 30
  content = lastLineOf(message)
  if(content.length > maxLen) {
    $('action-log-bar').innerHTML = content.substring(0, maxLen) + '...' 
  }else {
    $('action-log-bar').innerHTML = content
  }
}

function lastLineOf(message) {
  message = strip(message)
  index = message.lastIndexOf('\n')
  if(index > -1) {
    return message.substring(index, message.length)
  }
  return message
}

function loadCcMonitor() {
  requestSource($('ccmonitor_uri').value, updateLocalMonitor)
}
function saveLocalCcMonitor() {
  var monitor = getLocalMonitorValue()
  if(window.widget) {
    if(monitor == null) {
      monitor = ''
    }
    var command = window.widget.system('echo "' + monitor.replace(/"/g, '\\"') + '" > ' + localCcMonitor, null);
  }else {
    alert(monitor)
  }
}

function openRuntimeLog() {
  if(window.widget) {
    var base = window.widget.system('/bin/pwd', null).outputString
    var logFileUri = 'file://' + strip(base) + '/runtime.log'
    window.widget.openURL(logFileUri)
  }
}

function requestSource(uri, callback) {
  var transport = new XMLHttpRequest();
  transport.open('GET', uri, true);
  transport.onreadystatechange = function() {
    var readyState = transport.readyState;
    if (transport.readyState == 4) {
      if(transport.responseText) {
        callback(transport)
      }else {
        alert("can't get cc monitor from source(" + uri + "), response text: " + transport.responseText);
      }
    }
  }
  
  transport.send(null);
}

function hideBack() {
  if($('front').style.display == 'none') {
    return;
  }
  $('back').hide();
}

function showBack() {
  $('back').style.display = 'block'
}

function updateLocalMonitor(transport) {
  setLocalMonitorValue(transport.responseText)
}

function setLocalMonitorValue(value) {
  document.getElementById('local_monitor').innerHTML = value;
}

function getLocalMonitorValue() {
  return $('local_monitor').value;
}
